package com.gframework.mybatis.util.generator.core.codegen.gen;

import com.gframework.mybatis.util.generator.core.codegen.NeedCanUpdate;
import com.gframework.mybatis.util.generator.core.codegen.NeedPrimaryKey;
import com.gframework.mybatis.util.generator.core.codegen.SqlOperatorGenerator;
import com.gframework.mybatis.util.generator.core.codegen.dom.java.FullyQualifiedJavaType;
import com.gframework.mybatis.util.generator.core.codegen.dom.java.JavaVisibility;
import com.gframework.mybatis.util.generator.core.codegen.dom.java.Method;
import com.gframework.mybatis.util.generator.core.codegen.dom.java.Parameter;
import com.gframework.mybatis.util.generator.core.codegen.dom.xml.Attribute;
import com.gframework.mybatis.util.generator.core.codegen.dom.xml.TextElement;
import com.gframework.mybatis.util.generator.core.codegen.dom.xml.XmlElement;
import com.gframework.mybatis.util.generator.core.conf.Column;
import com.gframework.mybatis.util.generator.core.conf.Configuration;
import com.gframework.mybatis.util.generator.core.conf.MetaData;
import com.gframework.mybatis.util.generator.core.type.MybatisMappingJavaType;

/**
 * 根据主键删除一条数据.
 * 
 * @since 1.0.0
 * @author Ghwolf
 */
public class DeleteById implements SqlOperatorGenerator,NeedCanUpdate,NeedPrimaryKey {

	@Override
	public XmlElement createSqlXml(MetaData table, Configuration config) {
		Column pk = table.getPrimaryKey();
		
		XmlElement xml = new XmlElement("delete");
		xml.addAttribute(new Attribute("id", "deleteById"));
		xml.addAttribute(new Attribute("parameterType", MybatisMappingJavaType.getMybatisJavaTypeName(pk.getJavaType())));
		xml.addComment("根据主键删除一条数据");

		xml.addElement(new TextElement("DELETE FROM"));
		
		XmlElement tableName = new XmlElement("include");
		tableName.addAttribute(new Attribute("refid", "tableName"));
		xml.addElement(tableName);
		
		XmlElement where = new XmlElement("where");
		where.addElement(new TextElement(pk.getColumnName() + " = #{" + pk.getFormatColumnName() + "}"));
		xml.addElement(where);

		return xml;
	}

	@Override
	public Method createMethod(MetaData table, Configuration config) {
		Column pk = table.getPrimaryKey();
		Method method = new Method("deleteById");
		method.setReturnType(FullyQualifiedJavaType.getIntInstance());
		method.setVisibility(JavaVisibility.PUBLIC);
		method.addParameter(new Parameter(new FullyQualifiedJavaType(pk.getJavaType().getName()),"id"));
		// XXX 后期有时间了添加注释
		return method;
	}

}
